<?php

require_once("dao/user_dao.php");

class auth_controller extends abstract_controller {

    function prepare_model($request_params, Smarty $smarty_obj) { 	
		
		if (isset($_GET['type'])){
			$type = htmlentities($_GET['type']);
			switch($type){
				case 'reg'  : $message = $this->reg();   break;
				case 'login': $message = $this->login(); break;
				default     : die("Ayaya, en feil oppstod (ugyldig type)");				
			}

			$_SESSION['message'] = $message;
			$from = isset($_POST['from']) ? htmlentities($_POST['from']) : "default";
			//header("Location: ?page=$from&action=$type");
			header("Location: ?page=$from");
			exit();
		}
		else die("type ikke spesifisert");
    }
    
    function reg(){
		$username = isset($_POST['username']) ? htmlentities($_POST['username']) : "";
		$password = isset($_POST['password']) ? htmlentities($_POST['password']) : "";
		$email    = isset($_POST['email'])    ? htmlentities($_POST['email'])    : "";
	
		if (!(empty($username) || empty($password) || empty($email))){
			if(user_dao::userExists($username)) {
				return "Bruker finnes fra før!";
			} else {
				if(user_dao::writeUser($username,$password,$email)) {
					return "Ny bruker skrevet";
				}
				else return "Noe gikk galt";
			}	
		}
		return "Alle felter må fylles inn.";
    }
	
	function login(){
		$username = isset($_POST['username']) ? htmlentities($_POST['username']) : "";
		$password = isset($_POST['password']) ? htmlentities($_POST['password']) : "";
		$from     = isset($_POST['from'])     ? htmlentities($_POST['from'])     : "";
		
		if (!(empty($username) || empty($password))){
			if(user_dao::readUser($username, $password)) {
				$_SESSION["user"] = $username;
		//		header("Location: ?page=$from");
		//		exit();
		
			if($username == "estimate" || $username == "halvor") {
				$_SESSION['admin'] = true;
			}
			
				return "Velkommen $username";
			} else {
				return "Feil brukernavn/passord.";
			}
		}
		else {
			return "Alle felter må fylles inn.";
		}
	}

}
?>